package com.wyp.didishige;

import android.app.Activity;
import android.app.Application;
import android.app.NotificationManager;
import android.content.Context;
import android.media.MediaPlayer;
import android.util.DisplayMetrics;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.wyp.didishige.config.SheQuConstants;
import com.wyp.didishige.utils.SharePreferenceUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobGeoPoint;

/**
 *
 * Created by horrywu on 2015/2/11.
 */
public class MyApplication extends Application {
    private static DisplayMetrics dm = new DisplayMetrics();
    NotificationManager notificationManager;
    MediaPlayer mediaPlayer;
    static List<Activity> list=new ArrayList<Activity>();
    public static MyApplication myApplication;
    public static BmobGeoPoint lastPoint = null;// 上一次定位到的经纬度
    public static long serverTime=0;
    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager=getNotificationManager();
        mediaPlayer=getMediaPlayer();
        myApplication=this;
        if (getApplicationInfo().packageName.equals(getMyProcessName())){
            //im初始化
            BmobIM.init(this);
            //注册消息接收器
            BmobIM.registerDefaultMessageHandler(new MessageHandler(this));
        }
        initImageLoader(getApplicationContext());
        SDKInitializer.initialize(getApplicationContext());
        initDirectory();
    }
    /**
     * 获取当前运行的进程名
     * @return
     */
    public static String getMyProcessName() {
        try {
            File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
            BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
            String processName = mBufferedReader.readLine().trim();
            mBufferedReader.close();
            return processName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 初始化目录
     */
    private void initDirectory(){
        if (!SheQuConstants.SHEQU_ROOT.exists()){
            if (SheQuConstants.SHEQU_ROOT.mkdirs()){
                if (!SheQuConstants.SHEQU_HEAD.exists()){
                    boolean re = SheQuConstants.SHEQU_HEAD.mkdirs();
                    Log.d("创建文件夹",re+"");
                }
            }
        }
    }

    public static void add(Activity activity){
        list.add(activity);
    }
    // 关闭每一个list内的activity
    public static void exit() {
        try {
            for (Activity activity : list) {
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static DisplayMetrics getDisplayMetrics(){
        return dm;
    }

    public static MyApplication getInstance(){
        return myApplication;
    }

    public static void initImageLoader(Context context){

        try {
            File cacheDir = StorageUtils.getOwnCacheDirectory(context,
                    "com.wyp.didishige/Cache");// 获取到缓存的目录地址
            // 创建配置ImageLoader(所有的选项都是可选的,只使用那些你真的想定制)，这个可以设定在APPLACATION里面，设置为全局的配置参数
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                    context)
                    // 线程池内加载的数量
                    .threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2)
                    .memoryCache(new WeakMemoryCache())
                    .denyCacheImageMultipleSizesInMemory()
                    .discCacheFileNameGenerator(new Md5FileNameGenerator())
                            // 将保存的时候的URI名称用MD5 加密
                    .tasksProcessingOrder(QueueProcessingType.LIFO)
                    .discCache(new UnlimitedDiscCache(cacheDir))// 自定义缓存路径
                            // .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                    .writeDebugLogs() // Remove for release app
                    .build();
            // Initialize ImageLoader with configuration.
            ImageLoader.getInstance().init(config);// 全局初始化此配置
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public NotificationManager getNotificationManager(){
        if (notificationManager==null){
            notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return notificationManager;
    }

    public synchronized MediaPlayer getMediaPlayer(){
        if (mediaPlayer==null){
            mediaPlayer=MediaPlayer.create(this, R.raw.notify);
        }
        return mediaPlayer;
    }

    // 单例模式，才能及时返回数据
    SharePreferenceUtil mSpUtil;
    public static final String PREFERENCE_NAME = "_sharedinfo";

    public synchronized SharePreferenceUtil getSpUtil() {
        if (mSpUtil == null) {
            String currentId = BmobIM.getInstance().getCurrentUid();
            String sharedName = currentId + PREFERENCE_NAME;
            mSpUtil = new SharePreferenceUtil(this, sharedName);
        }
        return mSpUtil;
    }



    public void logout(){
        BmobIM.getInstance().disConnect();
        BmobUser.logOut(this);
        exit();
    }
}
